//
//  SendViewController.m
//  WXWeibo
//
//  Created by liuwei on 16/1/26.
//  Copyright (c) 2016年 baidu. All rights reserved.
//

#import "SendViewController.h"
#import "ThemeButton.h"
#import "ThemeLabel.h"
#import "UIViewExt.h"
#import "MMDrawerController.h"
#import "LocationTableViewController.h"
#import "BaseNavigationController.h"
#import "AppDelegate.h"
#import "SinaWeibo.h"
#import "AFNetworking.h"
#import "ThemeImageView.h"
#import "DataService.h"
#import "FacePannel.h"
#import "FaceView.h"

@interface SendViewController () <SinaWeiboRequestDelegate, UINavigationControllerDelegate, FaceViewDelegate>


@property (nonatomic,strong)UIView *addressView;
@property (nonatomic, strong)UITextView *textView;
//@property (nonatomic, strong)UIImageView *selectImgView;
@property (nonatomic, strong)FacePannel *faceView;
@end


@implementation SendViewController{

    
    //2.工具栏
    UIView *_editorBar; //五个按钮的父视图
//    UIWindow *_progressWindow;
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    //监听键盘弹出的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self _createNavigationViews];
    [self _loadEditorViews];
//    [self _createFacePannel];
    
    
}



//- (void)_createFacePannel {
//    
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    _faceView = [[FacePannel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    _faceView.bottom = self.view.bottom - 64;
//    _faceView.hidden = YES;
//    
//    __weak UITextView *weakText = _textView;
//    [_faceView.faceView setBlock:^(NSString *str){
//        
//        
//        
//        weakText.text = [NSString stringWithFormat:@"%@%@",weakText.text,str];
//        
//    }];
//     [self.view addSubview:_faceView];
//}
- (FacePannel *)faceView {
    
    if (_faceView == nil) {
        _faceView = [[FacePannel alloc] initWithFrame:CGRectMake(0, kScreenHeight, 0, 0)];
        _faceView.faceView.delegate = self;
        [self.view addSubview:_faceView];
        
    }
    return _faceView;
}


- (void)showFaceView {
    
    [_textView resignFirstResponder];
    [UIView animateWithDuration:0.25 animations:^{
        
        self.faceView.transform = CGAffineTransformMakeTranslation(0, -(self.faceView.height + 64));
        _editorBar.bottom = self.faceView.top;
        _textView.height = kScreenHeight - _editorBar.height - self.faceView.height;
    }];
    
    
}

- (void)hideFaceView {
    
    [_textView becomeFirstResponder];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.faceView.transform = CGAffineTransformIdentity;
    }];
}

- (UIView *)addressView{
    
    if (_addressView == nil) {
        
        _addressView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        [_editorBar addSubview:_addressView];
        
        //compose_toolbar_5.png
        ThemeLabel *addressLable = [[ThemeLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        addressLable.font = [UIFont systemFontOfSize:12];
        addressLable.colorName = @"More_Item_Text_color";
        addressLable.tag = 101;
        [_addressView addSubview:addressLable];
        
        ThemeImageView *addressImg = [[ThemeImageView alloc] initWithFrame:CGRectMake(10, 5, 20, 20)];
        addressImg.imgName = @"compose_toolbar_5.png";
        [_addressView addSubview:addressImg];
        
        addressLable.left = addressImg.right;
    }
    return _addressView;
}

//界面显示时自动弹出键盘
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [_textView becomeFirstResponder];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    
}

#pragma mark - 键盘弹出的方法
- (void)keyboardShow:(NSNotification *)notification {
    

    
    CGRect keyBoardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat keyBoradHeight = keyBoardFrame.size.height;
    
    //求出textView和工具栏的高度
    _textView.height = kScreenHeight - keyBoradHeight - _editorBar.height - 65;

    _editorBar.top = _textView.bottom ;
    
    
}

//#pragma mark - 键盘消失的方法
//- (void)keyboardHide:(NSNotification *)notification {
//    
//    _editorBar.bottom = _faceView.top;
//    
//    
//}
#pragma mark - create UI  创建子视图
//1.创建导航栏上的视图
- (void)_createNavigationViews {
    
    //1.关闭按钮
    ThemeButton *closeButton = [[ThemeButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    closeButton.normalImageName = @"button_icon_close.png";
    [closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:closeButton];
    [self.navigationItem setLeftBarButtonItem:closeItem];
    
    //2.发送按钮
    ThemeButton *sendButton = [[ThemeButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    sendButton.normalImageName = @"button_icon_ok.png";
    [sendButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *sendItem = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    [self.navigationItem setRightBarButtonItem:sendItem];
    
}
//2.创建编辑工具栏的视图
- (void)_loadEditorViews {
    
    //1.创建输入框视图
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,0)];
    _textView.font = [UIFont systemFontOfSize:16.0f];
    _textView.backgroundColor = [UIColor clearColor];
    _textView.editable = YES;
    [self.view addSubview:_textView];

    //2.创建编辑工具栏,五个按钮的父视图
    _editorBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 55)];
    
    _editorBar.backgroundColor = [UIColor clearColor
                                  ];
    [self.view addSubview:_editorBar];
    
    //3.创建多个编辑按钮
    NSArray *imgs = @[
                      @"compose_toolbar_1.png",
                      @"compose_toolbar_4.png",
                      @"compose_toolbar_3.png",
                      @"compose_toolbar_5.png",
                      @"compose_toolbar_6.png"
                      ];
    for (int i=0; i<imgs.count; i++) {
        NSString *imgName = imgs[i];
        ThemeButton *button = [[ThemeButton alloc] initWithFrame:CGRectMake(15+(kScreenWidth/5)*i, 20, 40, 33)];
        [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 10+i;
        button.normalImageName = imgName;
        [_editorBar addSubview:button];
    }
}

- (void)sendWeibo {
    
    //1.利用SinaSDK实现网络请求，发送微博
//    NSDictionary *params = @{
//                             @"status" : _textView.text
//                             };
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    SinaWeiboRequest *request = [delegate.sinaweibo requestWithURL:@"statuses/update.json" params:[params mutableCopy] httpMethod:@"POST" delegate:self];
    
    /*
     网络请求的方式：
     1.iOS自带的控件NSURLSession  NSURLSessionDataTask
     2.AFNetworking
     3.自己封装的网络请求类

    */
    
    //2.使用AFNetworking实现微博的发送
    NSDictionary *params = @{
                                 @"status" : _textView.text,
                                 @"access_token" : delegate.sinaweibo.accessToken
                           };

    NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";
    
    [[AFHTTPSessionManager manager] POST:urlString parameters:[params mutableCopy] success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"发送成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发送失败");

    }];
    
    //3.对AFNetworking的二次封装，实现网络请求类
    
    
//    NSDictionary *params = @{
//                                 @"status" : _textView.text
//                                 };
//    
//    NSString *urlString = @"statuses/upload.json";
//    
//    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"beauty.jpg"], 1);
//    
//    NSDictionary *fileParams = @{
//                                 @"pic" : imageData
//                                 
//                                 };
//    
//    
//    
//    [DataService requestWithURL:urlString params:params fileData:fileParams httpMethod:@"post" success:^(NSURLSessionDataTask *task, id result) {
//         
//         NSLog(@"发送微博成功");
//         
//         
//     } failure:^(NSError *error) {
//         
//         NSLog(@"发送微博失败");
//         
//     }];
    
    
    
}

#pragma mark - SinaWeiboRequestDelegate
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
    NSLog(@"发送成功");
}


#pragma mark - 按钮事件
- (void)closeAction {
    
    //获取到容器类控制器,并关闭右侧控制器
    MMDrawerController *drawerCtrl = (MMDrawerController *)self.view.window.rootViewController;
    
    [drawerCtrl closeDrawerAnimated:YES completion:NULL];
 
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

//发送微博
- (void)sendAction:(UIButton *)btn{
    
    
    NSString *notify = nil;
    //内容判断，不能发送空微博和超过140个汉字的微博
    if (_textView.text.length <= 0) {
        
        notify = @"微博内容不能为空";
        
        
    } else if (_textView.text.length > 140) {
        
        notify = @"微博内容不能超过140个字";
    }
    
    if (notify) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:notify delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alertView show];
        
        return;
        
    }
    
    
    [self sendWeibo];
    
    [self closeAction];
    
    
    
}



//textView下方五个按钮的点击事件
- (void)clickAction:(UIButton *)btn {
    
    
    if (btn.tag == 13) { //定位
        
     
        LocationTableViewController *locationCtrl = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"locationCtrl"];
        
        
        //传递block
        //防止循环引用
        __weak SendViewController *weakSelf = self;
        locationCtrl.locationBlock = ^(NSString *address){
            
            //将位置信息显示在界面上
            __strong SendViewController *strongSelf = weakSelf;

            UILabel *addressLable = (UILabel *)[strongSelf.addressView viewWithTag:101];
            addressLable.text = address;
        };
        
        
        
        BaseNavigationController *navCtrl = [[BaseNavigationController alloc] initWithRootViewController:locationCtrl];
        
        [self presentViewController:navCtrl animated:YES completion:NULL];
        
        
        
    } else if (btn.tag == 10) { //拍照或者从相册获取图片实现带图片的微博发送
        
        //UIActionSheet UIAlertView --- >
        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertAction *photoLibraryAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //弹出UIImagePickerController
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            [alertCtrl dismissViewControllerAnimated:YES completion:NULL];
            
        }];
        
        [alertCtrl addAction:cameraAction];
        [alertCtrl addAction:photoLibraryAction];
        [alertCtrl addAction:cancelAction];
        
        [self presentViewController:alertCtrl animated:YES completion:NULL];
        
    }
    
    if (btn.tag == 14) {
        
    
        if ([_textView isFirstResponder]) {
            [self showFaceView];
        }else {
            
            [self hideFaceView];
        }
    }
    
}

- (void)faceViewDidSelectFace:(NSString *)faceName {
    
    if (faceName != nil) {
        
        _textView.text = [_textView.text stringByAppendingString:faceName];
        
    }
}

@end
